package br.com.foxline.atlasmobile;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import br.com.foxline.atlasmobile.dao.AnnexDao;
import br.com.foxline.atlasmobile.dao.DimensaoDao;
import br.com.foxline.atlasmobile.dao.EnderecoDao;
import br.com.foxline.atlasmobile.dao.GenericDao;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Annex;
import br.com.foxline.atlasmobile.entities.Dimensao;
import br.com.foxline.atlasmobile.entities.Endereco;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.enums.Comando;
import br.com.foxline.atlasmobile.enums.ComposicaoFamiliar;
import br.com.foxline.atlasmobile.enums.Ocupacao;
import br.com.foxline.atlasmobile.enums.RendaFamiliar;
import br.com.foxline.atlasmobile.enums.SituacaoImovel;
import br.com.foxline.atlasmobile.handler.CaptureActivity;

public class DadosFamiliaresActivity extends Activity {

	private static final int MAX = 2;

	private static String IMOVEL = "getimovel";

	// DAO
	private ImovelDao imovelDao;
	private AnnexDao annexDao;
	private DimensaoDao dimensaoDao;

	private Imovel imovel;

	private RadioGroup radioGroup;
	private LinearLayout linearLayout;
	private EditText editText;
	private TextView textTitle;

	private int aux;
	private int cont;

	private Integer checkId;

	private Annex annex;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_info_geral);

		imovelDao = new ImovelDao(getApplicationContext());
		annexDao = new AnnexDao(getApplicationContext());

		if (getIntent().getSerializableExtra(IMOVEL) != null) {
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);
		} else {
			imovel = new Imovel();
		}

		linearLayout = (LinearLayout) findViewById(R.id.linearMain);
		textTitle = (TextView) findViewById(R.id.textTitle);
		initComponents();

		if (!getIntent().getBooleanExtra("cont", false)) {
			cont = 1;
		} else {
			cont = MAX;
		}

		chooseOne();

	}

	private void initComponents() {
		radioGroup = new RadioGroup(this);
		linearLayout.removeAllViews();

		editText = new EditText(this);
		editText.setVisibility(EditText.INVISIBLE);

		linearLayout.addView(textTitle);
		linearLayout.addView(editText);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_info_geral, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.image:
			Intent intent = new Intent(this, GalleryIssues.class);
			intent.putExtra(IMOVEL, imovel);
			startActivity(intent);
			break;
		case R.id.image_capture:
			intent = new Intent(this, CaptureActivity.class);
			intent.putExtras(getIntent());
			startActivityForResult(intent, 100);
			break;
		case R.id.finalizar:
			dialogSituacao();
			break;
		case R.id.sair:
			intent = new Intent(this, MenuActivity.class);
			startActivity(intent);
			try {
				finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		break;
		default:
			break;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			dialogDescription();

			annex = (Annex) data.getSerializableExtra("annex");
			TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			annex.setUUID(tManager.getDeviceId());

			annex.setImovel(imovel);
			saveResponse(annex);

		}
	}

	public void saveResponse(final Annex annex) {

		final ProgressDialog dialog = ProgressDialog.show(this, "",
				"Carregando...", true);
		new Thread(new Runnable() {
			@Override
			public void run() {
				annex.setContent(encodeImg(annex.getUri()));
				dialog.dismiss();
			}
		}).start();

		annexDao.create(annex);

	}

	private String encodeImg(String str) {
		Uri uri = Uri.parse(str);
		Bitmap decodeSampledBitmapFromResource = Util
				.decodeSampledBitmapFromResource(uri, 500, 500);

		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		decodeSampledBitmapFromResource.compress(Bitmap.CompressFormat.JPEG,
				100, bytes);
		byte[] b = bytes.toByteArray();

		return android.util.Base64.encodeToString(b,
				android.util.Base64.DEFAULT);

	}

	public void dialogDescription() {
		AlertDialog.Builder editalert = new AlertDialog.Builder(this);

		editalert.setTitle("Descrição da Imagem");
		editalert.setMessage("");

		final EditText input = new EditText(this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT);
		input.setLayoutParams(lp);
		editalert.setView(input);

		editalert.setPositiveButton("Confirmar",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int whichButton) {
						annex.setDescription(input.getText().toString());
						annexDao.update(annex);
					}
				});

		editalert.show();

	}

	private OnCheckedChangeListener listener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {

			RadioButton radioButton = (RadioButton) group
					.findViewById(checkedId);

			radioButton.getTag();

			switch (cont) {
			case 1:
				imovel.setComposicaoFamiliar((ComposicaoFamiliar) radioButton
						.getTag());
				break;
			case 2:
				imovel.setRendaFamiliar((RendaFamiliar) radioButton.getTag());
				break;
			}

		}
	};

	public void save() {

		if (imovel.getId() == null) {
			imovelDao.create(imovel);
		} else {
			imovelDao.update(imovel);
		}

	}

	@Override
	public void onBackPressed() {
		previous(null);
	}

	public void next(View view) {
		save();

		if (cont >= 1 && (cont < MAX)) {
			cont++;
			initComponents();
			chooseOne();

		} else if (cont >= MAX) {

			Intent intent = new Intent(getApplicationContext(),
					CorrespondenciaActivity.class);
			intent.putExtra(IMOVEL, imovel);
			startActivity(intent);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			finish();
		}

	}

	public void previous(View view) {
		save();

		cont = cont > MAX ? MAX : cont;
		if (cont > 1 && cont <= MAX) {
			cont--;
			initComponents();
			chooseOne();
		} else if (cont <= 1) {
			Intent intent = new Intent(getApplicationContext(),
					ProprietarioActivity.class);
			intent.putExtra(IMOVEL, imovel);
			startActivity(intent);
			finish();
		}

	}

	private void chooseOne() {
		aux = 0;
		checkId = null;

		radioGroup = new RadioGroup(this);

		radioGroup.setOnCheckedChangeListener(listener);

		switch (cont) {
		case 1:
			textTitle.setText("Composição Familiar ");
			genComposicaoFamiliar();
			break;
		case 2:
			textTitle.setText("Renda Familiar (em Salário)");
			genRendaFamiliar();
			break;
		}

		linearLayout.addView(radioGroup);
	}

	private void genComposicaoFamiliar() {
		for (ComposicaoFamiliar oc : ComposicaoFamiliar.values()) {

			RadioButton radioButton = new RadioButton(this);

			radioButton.setText(oc.getNome());
			radioButton.setTag(oc);

			radioGroup.addView(radioButton);
			if (imovel.getComposicaoFamiliar() != null
					&& imovel.getComposicaoFamiliar() == oc) {
				checkId = aux;
			} else {
				aux++;
			}
		}

		if (checkId != null)
			radioGroup.check(radioGroup.getChildAt(checkId).getId());
	}

	private void genRendaFamiliar() {
		for (RendaFamiliar oc : RendaFamiliar.values()) {

			RadioButton radioButton = new RadioButton(this);

			radioButton.setText(oc.getNome());
			radioButton.setTag(oc);

			radioGroup.addView(radioButton);
			if (imovel.getRendaFamiliar() != null
					&& imovel.getRendaFamiliar() == oc) {
				checkId = aux;
			} else {
				aux++;
			}
		}

		if (checkId != null)
			radioGroup.check(radioGroup.getChildAt(checkId).getId());
	}

	public void dialogSituacao() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Situação do Imóvel");

		final String[] items = new String[SituacaoImovel.values().length];
		int cont = 0;
		final Map<Integer, SituacaoImovel> map = new HashMap<Integer, SituacaoImovel>();

		for (SituacaoImovel si : SituacaoImovel.values()) {
			items[cont] = si.toString();
			map.put(cont, si);
			cont++;
		}

		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				imovel.setSituacaoImovel(map.get(which));
				save();
				imovel.getSituacaoImovel();
				finalCadastro();
			}
		});

		AlertDialog dsituacao = builder.create();
		dsituacao.show();
	}

	public void finalCadastro() {

		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setNeutralButton("Finalizar e usar como modelo",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								CreateMainActivity.class);

						imovel.setId(null);

						if (imovel.getEnderecoImovel() != null)
							imovel.getEnderecoImovel().setId(null);
						if (imovel.getEnderecoCorrespondencia() != null)
							imovel.getEnderecoCorrespondencia().setId(null);
						if (imovel.getAnnex() != null) {
							imovel.setAnnex(null);
						}
						if (imovel.getDimensoes() != null) {
							imovel.getDimensoes().setId(null);
						}
						if (imovel.getProprietarios() != null) {
							for (Proprietario p : imovel.getProprietarios()) {
								p.setId(null);
							}
						}

						intent.putExtra(IMOVEL, imovel);

						startActivity(intent);
						finish();

					}
				});

		builder.setPositiveButton("Finalizar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								MenuActivity.class);
						startActivity(intent);
						finish();

					}
				});

		builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		builder.setMessage("Desejar finalizar o cadastro").setTitle(
				"Cadastro Finalizado");

		dialog = builder.create();
		dialog.show();
	}

}
